/**
 * Copyright (c) 2006-2009 Marwan Abi-Antoun, Jonathan Aldrich, Nels E. Beckman,    
 * Kevin Bierhoff, David Dickey, Ciera Jaspan, Thomas LaToza, Gabriel Zenarosa, and others.
 *
 * This file is part of Crystal.
 *
 * Crystal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Crystal is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Crystal.  If not, see <http://www.gnu.org/licenses/>.
 */
package edu.cmu.cs.crystal.analysis.npe.dumbvisitor;

import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.ArrayAccess;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldAccess;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.QualifiedName;

import edu.cmu.cs.crystal.AbstractCompilationUnitAnalysis;

/**
 * A very dumb null pointer analysis. It will just give a warning at every dereference.
 * 
 * @author ciera
 */
public class DumbNPEAnalysis extends AbstractCompilationUnitAnalysis {


	@Override
	public String getName() {
		return "Really dumb NPE analysis";
	}

	@Override
	public void analyzeCompilationUnit(CompilationUnit d) {
		//on every compilation unit, just run the visitor
		d.accept(new DumbNPEVisitor());
	}

	/**
	 * The visitor for the analysis.
	 * @author ciera
	 * @since Crystal 3.4.0
	 */
	public class DumbNPEVisitor extends ASTVisitor {

		@Override
		public void endVisit(ArrayAccess node) {
			getReporter().reportUserProblem(node.getArray() + " may be null.", node, getName());
		}

		@Override
		public void endVisit(FieldAccess node) {
			if (node.getExpression() != null)
				getReporter().reportUserProblem(node.getExpression() + " may be null.", node, getName());
		}

		@Override
		public void endVisit(MethodInvocation node) {
			if (node.getExpression() != null)
				getReporter().reportUserProblem(node.getExpression() + " may be null.", node, getName());
		}

		@Override
		public void endVisit(QualifiedName node) {
			//Due to an ambiguity within the parser, a qualified name may actually be a FieldAccess.
			//To check for this, see what the binding is.
			if (node.resolveBinding() instanceof IVariableBinding) {
				//now we know it's field access.
				getReporter().reportUserProblem(node.getQualifier() + " may be null.", node, getName());
			}
		}
	}
}
